package com.openxu.calendar;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.androidkun.xtablayout.XTabLayout;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    private static final String TAG = "TestActivity";
    private CustomCalendar cal;
    private CalendarPagerAdapter pagerAdapter;
    private List<View> calendarViewList;
    private MyViewPager viewPager;
    private CustomCalendar customCalendar;
    //private List<MonthModel> canlendarDayList;

    private Map<String, List<Integer>> yearMap = new LinkedHashMap<>();
    private Map<String, List<DayModel>> monthMap = new LinkedHashMap<>();
    private Map<String, List<DataModel>> dayMap = new LinkedHashMap<>();
    private List<String> yearList;

    //private Map<String, Boolean> dotStateMap = new LinkedHashMap<>();
    //private Map<Integer, List<Integer>> months;
    //private Map<String, Boolean> dots;
    private TextView tv_canlendar;
    private int todayYear, todayMonth, todayDay;
    private int selectYear = 2018;

    private XTabLayout mTab;
    private List<String> monthTitle;
    private String recordMonth;
    private int recordDay;
    private OkHttpClient client;
    private int index;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    refreshDataAndView(index);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        setFakeData();
    }

    private void initData()
    {
        yearList = new ArrayList<>();
        //months = new LinkedHashMap<>();
        //dots = new LinkedHashMap<>();
        long curTime = System.currentTimeMillis();
        String curDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(curTime));
        String[] d = curDate.split("-");
        todayYear = Integer.parseInt(d[0]);
        todayMonth = Integer.parseInt(d[1]);
        todayDay = Integer.parseInt(d[2]);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        int subYear = 0;
        int subMonth = 0;

        int endYear = 2019;
        int endMonth = 8;
        if (todayMonth - 6 > 0)
        {
            subYear = todayYear;
            subMonth = todayMonth - 6;
        } else
        {
            subYear = todayYear - 1;
            subMonth = todayMonth + 12 - 6;
        }
        for (int i = subYear; i <= endYear; i++)
        {
            //List<MonthModel> monthList2 = new ArrayList<>();
            List<Integer> monthList1 = new ArrayList<>();
            int startMon = 1;
            int endMon = 12;
            if (i == todayYear)
            {
                startMon = subMonth;
            }
            if (i == endYear)
            {
                endMon = endMonth;
            }

            for (int j = startMon; j <= endMon; j++)
            {
                MonthModel monthModel = new MonthModel();
                monthModel.setMonthId(i+"-"+j);
                //monthList2.add(monthModel);

                monthList1.add(j);

                List<DayModel> dayList = new ArrayList<>();
                try {
                    int days = getDaysOfMonth(sdf.parse(i+"-"+j));
                    for (int k=1;k<=days;k++){
                        DayModel dayModel = new DayModel();
                        dayModel.setDayId(i+"-"+j+"-"+k);
                        List<DataModel> dataList = new ArrayList<>();
                        dayList.add(dayModel);
                        dayModel.setData(dataList);
                        dayMap.put(i+"-"+j+"-"+k,dataList);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                monthModel.setDays(dayList);
                monthMap.put(i+"-"+j,dayList);
            }
            yearMap.put(String.valueOf(i),monthList1);
            yearList.add(i + "");

            //months.put(i, monthList1);
         }
        Log.d(TAG, "initData: -----");

        mTab.setTabMode(TabLayout.MODE_SCROLLABLE);
        initTablayoutData(todayYear);


        pagerAdapter = new CalendarPagerAdapter();
        viewPager.setAdapter(pagerAdapter);
        //int index = getMonthIndex(todayYear, months.get(todayYear));
        index = getMonthIndex(todayYear, yearMap.get(String.valueOf(todayYear)));
        viewPager.setCurrentItem(index);
        Log.d(TAG, "initData: ------");
        mTab.setupWithViewPager(viewPager);

    }

    //月份选择tablayout
    private void initTablayoutData(int year)
    {
        mTab.removeAllTabs();
        monthTitle = new ArrayList();
//        for (int i = 0; i < months.get(year).size(); i++)
//        {
//            monthTitle.add(months.get(year).get(i) + "月");
//        }
        for (int i = 0; i < yearMap.get(year+"").size(); i++)
        {
            monthTitle.add(yearMap.get(year+"").get(i) + "月");
        }
    }

    private View getTabView(int i) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_month,null,false);
        TextView tvItemMonth = (TextView) view.findViewById(R.id.tv_item_month);
        tvItemMonth.setText(monthTitle.get(i));
        return view;
    }

    public static int getDaysOfMonth(Date date)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }


    //模拟假数据
    private void setFakeData()
    {
        client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Urls.SERVER_URL+"abc/abc.json")
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e(TAG, "onFailure: -----"+e.toString() );
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()){
                    String result = response.body().string();
                    Gson gson = new Gson();
                    BaseListModel baseListModel = gson.fromJson(result, BaseListModel.class);
                    Log.d(TAG, "onResponse: ----"+result);
                    List<MonthModel> list = baseListModel.getList();
                    //List<MonthModel> monthList = new ArrayList<>();
                    //String mYear = "";
                    for (MonthModel monthModel:list){
                        String monthId = monthModel.getMonthId();
                        String[] date = monthId.split("-");
                        String year = date[0];
                        String month = date[1];

                        List<DayModel> days1 = monthModel.getDays();
                        for (DayModel dayModel:days1){
                            String dayId = dayModel.getDayId();
                            String[] date1 = dayId.split("-");
                            String day = date1[2];

                            List<DataModel> data = dayModel.getData();
                            if (data != null && data.size() >0) {
                                dayMap.put(dayId,data);
                            }
                        }
                        monthMap.put(monthId,days1);

                    }
                    Log.d(TAG, "onResponse: -----");
                    handler.sendEmptyMessage(1);
                }
            }
        });
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//        int chooseYear = selectYear;
//        canlendarDayList = new ArrayList<>();
//        for (int i = 1; i <= 12; i++)
//        {
//
//            try
//            {
//                int days = getDaysOfMonth(sdf.parse(String.valueOf(chooseYear + "-" + i)));
//
//                for (int j = 0; j < days; j++)
//                {
//                    if (j % 2 == 0)
//                    {
//                        //这里进行数据的状态更改
//                        dots.put(chooseYear + "年" + i + "月" + j + "日", true);
//                    }
//                }
//            } catch (ParseException e)
//            {
//                e.printStackTrace();
//            }
//
//        }
//        Log.d(TAG, "setFakeData: ");
//        long curTime = System.currentTimeMillis();
//        String date = new SimpleDateFormat("yyyy年MM月").format(new Date(curTime));
        //customCalendar.setRenwu(date, dots);
    }


    private void setCustomCalendarOnclick()
    {
        customCalendar.setOnClickListener(new CustomCalendar.onClickListener()
        {
            @Override
            public void onLeftRowClick()
            {

            }

            @Override
            public void onRightRowClick()
            {

            }

            @Override
            public void onTitleClick(String monthStr, Date month)
            {

            }

            @Override
            public void onWeekClick(int weekIndex, String weekStr)
            {

            }

            @Override
            public void onDayClick(int day, String dayStr, List<DataModel> dataList)
            {
                if (dataList != null && dataList.size()>0) {
                    Toast.makeText(MainActivity.this, "点击了日期：" + dayStr + day + "日" + "---有数据" , Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "点击了日期：" + dayStr + day + "日" + "---无数据" , Toast.LENGTH_SHORT).show();
                }
                Log.w("", "点击了日期:" + dayStr);
                recordMonth = dayStr;
                recordDay = day;
            }

        });
    }

    private void initView()
    {
        mTab = (XTabLayout) findViewById(R.id.main_tab);

        tv_canlendar = (TextView) findViewById(R.id.tv_canlendar);
        tv_canlendar.setOnClickListener(this);
        viewPager = (MyViewPager) findViewById(R.id.viewpager);
        setCalendarViewListData(12);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {
                Log.d(TAG, "onPageScrolled: ------");
            }

            @Override
            public void onPageSelected(int position)
            {
                refreshDataAndView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state)
            {

            }
        });

    }

    private void refreshDataAndView(int position) {
        customCalendar = (CustomCalendar) calendarViewList.get(position).findViewById(R.id.calendar);
        setFakeData();
        int month = yearMap.get(String.valueOf(selectYear)).get(position);
        String date = selectYear+"年"+month+"月";
        customCalendar.setRenwu(date, recordMonth, recordDay, dayMap);
        setCustomCalendarOnclick();
    }

    //count为需要展示多少个月
    private void setCalendarViewListData(int count)
    {
        calendarViewList = new ArrayList<>();
        for (int i = 0; i < count; i++)
        {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.canlendar_view, null);
            calendarViewList.add(view);
        }
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.tv_canlendar:
                SelectYearPopupWindow popupWindow = new SelectYearPopupWindow(
                        MainActivity.this, yearList, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View view)
                    {
                        selectYear = (Integer) view.getTag();
                        tv_canlendar.setText(selectYear + "");
                        changeYear(selectYear);
                    }
                });
                popupWindow.showAtLocation(tv_canlendar, Gravity.BOTTOM, 0, 0);
                break;
        }
    }

    //用于viewpager
    private int getMonthIndex(int year, List<Integer> data)
    {
        int index = 0;
        if (year == todayYear)
        {
            //切换年到今年，直接跳到当月
            for (int i = 0; i < data.size(); i++)
            {
                if (data.get(i) == todayMonth)
                {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }

    //年份切换
    private void changeYear(int year)
    {

        List<Integer> monthlist = yearMap.get(String.valueOf(year));
        initTablayoutData(year);
        setCalendarViewListData(monthlist.size());
        pagerAdapter.notifyDataSetChanged();
        int index = getMonthIndex(year, monthlist);
        viewPager.setCurrentItem(index);
    }

    public class CalendarPagerAdapter extends PagerAdapter
    {

        public CalendarPagerAdapter()
        {
        }

        private int mChildCount = 0;

        @Override
        public void notifyDataSetChanged()
        {
            mChildCount = getCount();
            super.notifyDataSetChanged();
        }

        @Override
        public int getCount()
        {
            return calendarViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            View view = calendarViewList.get(position);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView((View) object);
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            if (position > monthTitle.size() - 1)
            {
                return "";
            }

            return monthTitle.get(position);



        }
    }
}
